using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace SpriteAnimations.Graphics
{
    class AnimationManager
    {
        //
        // Fields
        //
        private Sprite boundSprite;
        private List<SpriteAnimation> animations;

        //
        // Constructors
        //
        public AnimationManager(Sprite boundSprite)
        {
            this.boundSprite = boundSprite;
            this.animations = new List<SpriteAnimation>();
        }

        //
        // Public Methods
        //
        public void Add(SpriteAnimation animation)
        {
            animation.SetAnimatedSprite(boundSprite);
            animations.Add(animation);
        }

        public SpriteParameters Animate(TimeSpan gameTime)
        {
            SpriteParameters animatedParameters = (SpriteParameters)boundSprite.Parameters.Clone();

            //is there no texture animation, draw the total texture
            if (animatedParameters.m_iHeight == 0 && animatedParameters.m_iWidth == 0)
            {
                animatedParameters.m_iWidth = boundSprite.Image.Width;
                animatedParameters.m_iHeight = boundSprite.Image.Height;
            }

            if (animations.Count > 0)
            {
                // Process attached animations
                SpriteAnimation currentAnimation = animations[0];
                currentAnimation.Animate(gameTime, animatedParameters);

                if (currentAnimation.IsFinished)
                {
                    animations.RemoveAt(0);
                }
            }

            // Auto adjust location if we are rotating. 
            // This will force a rotation around the center of the image rather than the top left
            if (animatedParameters.Rotation > 0)
            {
                Vector2 center = new Vector2(boundSprite.Image.Width / 2,
                    boundSprite.Image.Height / 2);

                animatedParameters.Origin = center;
                animatedParameters.Position += center;
            }

            return animatedParameters;
        }
    }
}
